<template>
  <base-page-view class-name="b-goods-container">
    <!--#ifndef H5  -->
    <base-nav :nav-holder="false" left-icon="back" :title="title" :background="`rgba(255,255,255, ${pageScrollTop > 50 ? 1 : pageScrollTop / 55})`">
    </base-nav>
    <!-- #endif -->
    <!--#ifdef H5  -->
    <view class="back-btn" @click="toBackPage">
      <image src="/static/images/icon/icon_back.png" />
    </view>
    <!-- #endif -->
    <base-swiper class-name="goods-swiper" :swiper-list="goods.slideImageUrls" :show-dots="false" :show-index="true" border-radius="0" @itemClick="goodsPicClick"></base-swiper>
    <template v-if="!pageLoading">
      <view class="info-block base-info">
        <view class="goods-name" @longpress="copyText">
          <view class="platform" :class="'platform-'+pageQuery.platform">{{ platformType[pageQuery.platform] }}</view>{{ goods.title }}
        </view>
        <view v-if="goods.name" class="rule-box" @longpress="copyText">
          <view class="rule-text">{{ goods.name }}</view>
          <view class="rule-btn" @click="checkRules">查看规则</view>
        </view>
        <view class="between-block">
          <view class="goods-price">
            <view class="price">{{ goods.actualPrice }}<view class="price-text">{{ pageQuery.platform==='VOP'?'折':'券' }}后价</view></view>
            <view class="original-price">原价￥{{ goods.originalPrice }}</view>
          </view>
          <view v-if="pageQuery.platform!=='VOP'" class="month-sales">月销{{ goods.monthSales }}</view>
        </view>
        <view class="commission-block" :style="'background-image: url('+vipBg+')'" v-if="show_vip">
          <view>{{ commissionText }}</view>
          <view class="btn" v-if="userInfo.current_member_card_type>=2" @click="$navigateTo('/pagesMember/member/index')">会员中心</view>
          <view v-else @click="$navigateTo('/pagesMember/pay/index?type=diamond')">立即升级</view>
        </view>
        <view v-if="goods.hasCoupon === 1" class="coupon-block">
          <view class="left">
            <image :src="couponBg.left" mode="widthFix" />
            <view class="content">
              <view>{{ goods.couponDiscount }}元优惠券</view>
              <template v-if="goods.couponUseStartTime && goods.couponUseEndTime">
                <view class="date">使用期限：{{ goods.couponUseStartTime }}~{{ goods.couponUseEndTime }}</view>
              </template>
            </view>
          </view>
          <view class="right" @click="handleBtnClick()">
            <image :src="couponBg.right" mode="widthFix" />
            <view class="content">立即领券</view>
          </view>
        </view>
        <view class="rights-block" :class="{ border: goods.hasCoupon === 1 }">
          <view class="rights-item">
            <image :src="selectIcon" mode="aspectFit" />
            <view>省钱精选</view>
          </view>
          <view class="rights-item">
            <image :src="selectIcon" mode="aspectFit" />
            <view>品质保证</view>
          </view>
          <view class="rights-item">
            <image :src="selectIcon" mode="aspectFit" />
            <view>售后无忧</view>
          </view>
        </view>
      </view>
      <view v-if="pageQuery.platform!=='VOP'" class="info-block recommend-info">
        <view class="title">推荐理由</view>
        <view class="content">
          <view v-for="(item, index) in goods.shareDesc" :key="index">{{ item }}</view>
        </view>
      </view>
      <view class="info-block shop-block">
        <view class="platform-line">
          <view class="platform" :class="'platform-'+pageQuery.platform">{{ platformType[pageQuery.platform] }}</view>{{ goods.shopNick }}
        </view>
        <view class="avg-line">
          <view class="avg-item">宝贝描述<view class="score">4.9</view><view class="level">高</view></view>
          <view class="avg-item">卖家服务<view class="score">4.9</view><view class="level">高</view></view>
          <view class="avg-item">物流服务<view class="score">4.9</view><view class="level">高</view></view>
        </view>
      </view>
      <view class="detail-block">
        <view class="title">宝贝详情</view>
        <view class="content">
          <b-image v-for="(item, index) in goods.detailUrl" :key="index" class-name="img" :src="item" mode="widthFix" />
        </view>
      </view>
      <view class="footer-block">
        <view class="btn-home" @click="$navigateTo('/pages/home/index', {}, 'reLaunch')">
          <image :src="homeIcon" mode="aspectFit" />
          <view>首页</view>
        </view>
        <view class="btn btn-share" @click="handleBtnClick('share')">分享赚￥{{ token?goods.commission:goods.diamondCommission | formatMoney }}</view>
        <view class="btn btn-buy" @click="handleBtnClick()">购买省￥{{ goods.benefitMoney }}</view>
      </view>
    </template>
    <share-type ref="shareType" :share-option="shareOption" :canvas-data="canvasData">
      <swiper class="image-list" previous-margin="100rpx" next-margin="100rpx" @change="change">
        <swiper-item v-for="(item, index) in goods.slideImageUrls" :key="index">
          <view class="image-item" :class="{active: currentImageIndex === index}">
            <view class="flex-container userinfo-block">
              <image class="avatar" :src="userInfo.head_img || '/static/images/mine/touxiang.png'" mode="aspectFill" />
              <view class="sub-item">
                <view>{{ userInfo.nickname }}</view>
                <view class="desc">推荐一个好物，快来抢嘿！</view>
              </view>
            </view>
            <view class="goods-block">
              <image class="goods-image" :src="item.pic" mode="aspectFit" />
              <view class="goods-name">
                <view class="platform" :class="'platform-'+pageQuery.platform">{{ platformType[pageQuery.platform] }}</view>{{ goods.title }}
              </view>
              <view class="between-block">
                <view class="goods-price">
                  <view class="price">{{ goods.actualPrice }}<view v-if="goods.hasCoupon === 1" class="price-text">券后价</view></view>
                  <view class="original-price">原价￥{{ goods.originalPrice }}</view>
                </view>
                <view v-if="goods.monthSales" class="month-sales">月销{{ goods.monthSales }}</view>
              </view>
            </view>
            <view v-if="goods.hasCoupon === 1" class="coupon-block">
              <view class="left">
                <image :src="couponBg.left" />
                <view class="content">
                  <view>{{ goods.couponDiscount }}元优惠券</view>
                  <view class="date">{{ goods.couponUseStartTime }}~{{ goods.couponUseEndTime }}</view>
                </view>
              </view>
              <view class="right" @click="handleBtnClick()">
                <image :src="couponBg.right" />
                <view class="content">
                  <image class="qr-code" :src="codeUrl" mode="aspectFit" />
                </view>
              </view>
            </view>
            <view v-else class="qr-code-block">
              <image class="qr-code no-coupon" :src="codeUrl" mode="aspectFit" />
              <view>长按或扫码购买</view>
            </view>
          </view>
        </swiper-item>
      </swiper>
    </share-type>
    <share ref="drawImage" :share-types="[1,3,5]" :share-option="shareOption" poster-type="commodity" />
    <modal ref="ruleModal" :title="ruleData.title" :content-no-line="ruleData.content" :btn-background="'#FF0C36'" />
  </base-page-view>
</template>
<script>
import { mapState } from 'vuex'
import baseSwiper from '@/components/base/base-swiper.vue'
import modal from '@/components/modal/index'
import share from '@/components/draw/share'
import shareType from '../components/shareType/index.vue'
import { createSharePathUrl, setClipboardData } from '@/utils/tools'
import './index.scss'
export default {
  name: 'BGoods',
  components: {
    baseSwiper,
    share,
    shareType,
    modal
  },
  data() {
    return {
      ruleData: {
        title: '活动规则',
        content: []
      },
      pageLoading: false,
      shareOption: {
        share_text: ''
      },
      shortUrl: '', // 分享短链接
      codeUrl: '', // 分享二维码/小程序码,
      canvasData: {}, // 二维码/小程序码绘制数据,
      pageScrollTop: 0, // 页面滑动距离
      title: '', // 页面标题
      platformType: { // 平台类型
        PDD: '拼多多',
        VOP: '唯品会'
      },
      commissionText: '',
      pageQuery: {},
      goodsImgs: [],
      goods: {
        slideImageUrls: [],
        detailUrl: [],
        shareDesc: []
      },
      currentImageIndex: 0,
      inviteData: null,
      vip_link: null,
      couponBg: {
        left: `${process.env.VUE_APP_IMAGE_ASSET}/images/biHuaSuan/coupon_left.png`,
        right: `${process.env.VUE_APP_IMAGE_ASSET}/images/biHuaSuan/coupon_right.png`
      },
      selectIcon: `${process.env.VUE_APP_IMAGE_ASSET}/images/biHuaSuan/icon_select.png`,
      homeIcon: `${process.env.VUE_APP_IMAGE_ASSET}/images/biHuaSuan/icon_home.png`,
      vipBg: `${process.env.VUE_APP_IMAGE_ASSET}/images/biHuaSuan/bg_vip.png`,
      show_vip:false
    }
  },
  computed: {
    ...mapState([
      'token',
      'userInfo'
    ])
  },
  async onLoad(options) {
    this.pageQuery = { ...options }
    const res = await this.$api.homeApi.getHomeDetail({
      hideLoading: true
    })
    if(res&&res.data&&res.data.menuList){
    	for (let s of res.data.menuList) {
    		if(s.name=='会员升级'){
    			this.show_vip=true;
    		}
    	}
    }
  },
  onShow() {
    this.fetchData()
  },
  onPageScroll(res) {
    // #ifndef h5
    if (res) {
      this.pageScrollTop = res.scrollTop
      this.title = this.pageScrollTop > 10 ? '商品详情' : ''
      const color = this.pageScrollTop > 10 ? '#000000' : '#ffffff'
      uni.setNavigationBarColor({
        frontColor: color,
        backgroundColor: '#ffffff'
      })
    }
    // #endif
  },
  onShareAppMessage(res) {
    return this.$queryShareOption(res, this.shareOption)
  },
  methods: {
    checkRules() {
      this.ruleData.content = this.goods.rules || []
      this.$refs.ruleModal.show()
    },
    async fetchData(refreshFlag) {
      this.pageLoading = !refreshFlag
      const res = await this.$api.biHuaSuanApi.getGoodsDetail(this.pageQuery)
      if (res.success && res.data) {
        const { detailUrl, shareDesc, commission, couponDiscount, couponUseStartTime, couponUseEndTime } = res.data
        this.goodsImgs = res.data.slideImageUrls ? res.data.slideImageUrls.split(',') : []
        const slideImageUrls = this.goodsImgs.map(i => ({ pic: i, shareImg: '' }))
        const params = {
          price: res.data.actualPrice
        }
        let resRule = null
        if (this.token) resRule = await this.$api.biHuaSuanApi.getGoodsCoupon(params)
        this.goods = {
          ...res.data,
          slideImageUrls,
          detailUrl: detailUrl ? detailUrl.split(',') : [],
          shareDesc: shareDesc ? shareDesc.split('\n') : [],
          benefitMoney: (commission + couponDiscount).toFixed(2),
          couponUseStartTime: couponUseStartTime ? couponUseStartTime.split(' ')[0] : '',
          couponUseEndTime: couponUseEndTime ? couponUseEndTime.split(' ')[0] : '',
          name: (resRule && resRule.success && resRule.data) ? resRule.data.name : '',
          rules: (resRule && resRule.success && resRule.data) ? resRule.data.rules : []
        }
        if (this.userInfo.current_member_card_type >= 2) {
          this.commissionText = `您是${['', '', '钻石', '董事'][this.userInfo.current_member_card_type]}会员，本单可奖励 ${this.goods.commission}元`
        } else {
          this.commissionText = `升级钻石会员，本单可奖励${this.goods.diamondCommission}元`
        }
      }
      this.pageLoading = false

      // #ifdef H5
      if (this.goods.platform === 'VOP') {
        this.initShareDetail('share', true)
      }
      // #endif
    },
    goodsPicClick({ index }) {
      uni.previewImage({
        current: index,
        urls: this.goodsImgs
      })
    },
    // 去拼多多授权
    toAuthPdd (data) {
      this.$gc.$message({
          title: '提 示',
          content: '请先前往拼多多进行授权',
          confirmText: '去授权',
          align: 'center',
          confirm: () => {
            // #ifdef H5
            window.open(data.h5AppOauthUrl, '_blank')
            // #endif
            // #ifdef MP-WEIXIN
            // /pages/web/web?specialUrl=1&src=https%3A%2F%2Fmobile.yangkeduo.com%2Fduo_coupon_landing.html%3F__page%3Dauth%26pid%3D8821067_210779535%26cpsSign%3DCC_210601_8821067_210779535_35e9d942f0aaeed161184e48fd91c7bc%26duoduo_type%3D2
            uni.navigateToMiniProgram({
                appId: data.weAppInfo.appId,
                path: data.miniOauthUrl,
            })
            // #endif
          }
        })
    },
    async initShareDetail(type, initFlag) {
      const postData = {
        goodsId: this.goods.goodsId,
        title: this.goods.title,
        actualPrice: this.goods.actualPrice,
        commission: this.goods.commission,
        couponLink: this.goods.couponLink || '',
        hasCoupon: this.goods.hasCoupon,
        imageUrl: this.goods.imageUrl,
        originalPrice: this.goods.originalPrice,
        platform: this.goods.platform,
        generateWeApp: process.env.VUE_APP_PLATFORM !== 'h5',
        inviteCode: this.userInfo ? this.userInfo.invite_code : ''
      }
      if (this.pageQuery.share_code && type !== 'share') {
        postData.targetInviteCode = this.pageQuery.share_code
      }
      if (!(!this.pageQuery.share_code && this.inviteData)) {
        const res = await this.$api.biHuaSuanApi.getShareUrl(postData)
        if(res.success && res.data.hasOauth===0 && res.data.platform === "PDD" ){
          this.toAuthPdd(res.data)
          return
        }
        if (res.success && res.data) {
          this.inviteData = res.data
          this.initShare()
        }
      }

      if (type === 'share') {
        // #ifdef H5
        if (!initFlag) {
          if (this.goods.platform === 'VOP') {
            setClipboardData({
              data: this.shareOption.share_text,
              success: () => {
                uni.showToast({
                  title: '文案已复制成功',
                  icon: 'none',
                  duration: 1500
                })
              }
            })
          } else {
            this.$refs.drawImage.show(this.shareOption)
            // this.$refs.shareType.show()
          }
        }
        // #endif

        // #ifndef H5
        this.$refs.drawImage.show(this.shareOption)
        // this.$refs.shareType.show()
        // #endif
        return
      }

      // #ifdef H5
      location.href = this.inviteData.shareUrl
      // #endif

      // #ifdef MP-WEIXIN
      if (this.inviteData.weAppInfo) {
        uni.navigateToMiniProgram({
          appId: this.inviteData.weAppInfo.appId,
          path: this.inviteData.weAppInfo.pagePath,
          extraData: {
            'data1': 'test'
          },
          success(res) {
            // 打开成功
          }
        })
      }
      // #endif
    },
    handleBtnClick(type) {
      if (this.token) {
        switch (type) {
          case 'vip':
            this.initVip()
            break
          default:
            this.initShareDetail(type)
        }
      } else {
        this.$navigateTo('/pages/login/index')
      }
    },
    change({ detail }) {
      this.currentImageIndex = detail.current
      this.initCanvasData()
    },
    async initVip() {
      if (!this.vip_link) {
        const res = await this.$api.promoteApi.getVipUrl({
          userRole: this.userInfo.current_member_card_type + ''
        })
        if (res.success && res.data) {
          if (res.data.vip_link && res.data.vip_link.indexOf('.bisinuolan.cn') > -1) {
            const params = res.data.vip_link.split('.bisinuolan.cn')
            this.vip_link = params[1]
          }
        }
      }
      this.$navigateTo(this.vip_link)
    },
    initShare() {
      if (this.token && this.inviteData && this.goods) {
        this.shareOption.share_url = this.shortUrl
        this.shareOption.share_title = this.goods.title
        this.shareOption.share_content = this.goods.shareDesc[0]
        if (this.goods.imageUrl) {
          this.shareOption.share_icon = this.goods.imageUrl
          this.shareOption.share_image = this.goods.imageUrl
        }
        this.shareOption.share_list = this.goods.slideImageUrls.map(item => {
          return {
            pic: item.pic,
            title: this.goods.title || '',
            price: this.goods.actualPrice || 0,
            original: this.goods.originalPrice || 0,
            platform: this.goods.platform
          }
        })
        this.initShareText()
        this.showShare()
      } else {
        this.hideShare()
      }
    },
    // 小程序码获取
    async getWeinCode() {
      const path = createSharePathUrl()
      const res = await this.$api.commonApi.queryMiniCode({
        page: 'pages/share/index',
        scene: encodeURIComponent(path),
        width: 430
      })
      if (res.success && res.data) {
        this.initShareImg(res.data.file_path)
      }
    },
    initCanvasData() {
      let title = this.goods.title
      if (title && title.length > 18) {
        title = title.slice(0, 18) + '...'
      }
      this.canvasData = {
        avatar: this.userInfo.head_img,
        nickname: this.userInfo.nickname,
        goodsImage: this.goods.slideImageUrls[this.currentImageIndex],
        platform: this.goods.platform,
        platformName: this.platformType[this.goods.platform],
        title,
        actualPrice: this.goods.actualPrice,
        originalPrice: this.goods.originalPrice,
        hasCoupon: this.goods.hasCoupon,
        couponDiscount: this.goods.couponDiscount,
        monthSales: this.goods.monthSales,
        couponUseStartTime: this.goods.couponUseStartTime ? this.goods.couponUseStartTime.split(' ')[0] : '',
        couponUseEndTime: this.goods.couponUseEndTime ? this.goods.couponUseEndTime.split(' ')[0] : '',
        codeUrl: this.codeUrl
      }
    },
    initShareImg(val) {
      this.codeUrl = val
      this.initCanvasData()
    },
    async initShareText() {
      const { buyerUrl, shareContent } = this.inviteData
      const { goodsInfo, shareGoodsUrl } = shareContent/*
      const url = this.shareOption.page_path ? (`${process.env.VUE_APP_PRE_URL}${this.shareOption.page_path}`) : this.shareOption.share_url
      const res = await this.$api.goodsApi.shortUrl({
        longurl: url
      })
      this.shortUrl = res.data || url */
      this.shortUrl = buyerUrl
      const goodsBuyLink = this.goods.platform === 'VOP' ? shareGoodsUrl : `——————————————\n${shareGoodsUrl}`
      this.shareOption.share_text = goodsInfo + goodsBuyLink

      // // #ifdef MP-WEIXIN
      // this.getWeinCode()
      // // #endif

      // // #ifdef H5
      // setTimeout(() => {
      //   this.$refs.qrcode._makeCode()
      // }, 100)
      // // #endif
    },
    copyText() {
      setClipboardData({
        data: this.goods.title,
        fail: (e) => {
          console.log(e)
        }
      })
    },
    toBackPage() {
      /* eslint-disable-next-line */
      const pages = getCurrentPages()
      if (pages.length < 2) {
        uni.reLaunch({ url: '/pagesBHS/home/index' })
      } else {
        uni.navigateBack()
      }
    }
  }
}
</script>
